#include "mex.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>

int Pmap(int i, int j, int NIe, int NJe, int NIt){
    int index;
    int block1,is,js;
    
    if ( j <= NJe )
        index = i + (j-1) * NIt;
    else{
        block1 = NIt*NJe;
        is = i-NIe;
        js = j-NJe;
        index = block1 + is + (NIt-NIe) * (js-1);
        if (is<1 || js<1)
            mexErrMsgTxt("Vmap : Access to V(i,j) out of bounds. \n");
    }
    return index;
}

/*
 * index = Pmap(i, j, NIe, NJe, NIt)
 * 
 * 
 *
 */

void mexFunction( int nlhs, mxArray *plhs[], 
		 int nrhs, const mxArray *prhs[] )
{
   int i, j;
   int NIe, NJe, NIt;
   
   double *index;
   
   mwSignedIndex outputSize[1]; 
      
   outputSize[0] = 1;
   
   /* Check for proper number of arguments */
   if ( nlhs != 1) 
      mexErrMsgTxt("Wrong number of output arguments.");
   if ( nrhs != 5 )
      mexErrMsgTxt("Wrong number of input arguments.");
                 
   /* Assign pointers to each input and output */
   i = *(double *)mxGetPr(prhs[0]); 
   j = *(double *)mxGetPr(prhs[1]);
   NIe = *(double *)mxGetPr(prhs[2]);
   NJe = *(double *)mxGetPr(prhs[3]);
   NIt = *(double *)mxGetPr(prhs[4]);

   plhs[0] = mxCreateNumericArray(1, outputSize, mxDOUBLE_CLASS, mxREAL);
   index = (double *) mxGetPr(plhs[0]);   

/*   #pragma omp parallel for private(xt,yt,ang,dAng,frame,maxEnergy) default(shared) num_threads(omp_get_max_threads())
*/
    *index = Pmap (i  ,j , NIe, NJe, NIt );
   
    return;
}


